package com.yehongyu.mytools.database.connectdb;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class ConnectDB {
	/**
	 * 构造方法
	 *
	 */
	public ConnectDB() {
		super();
	}

	/**
	 * 用JDBC方式从Orcale获取连接
	 * @return conor
	 */
	public Connection getConnectionFromOracle() {
		Connection conor = null;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
			String url = "jdbc:oracle:thin:@localhost:1521:orcl";
			// 获取数据库的连接
			String user = "yehy";
			String password = "yehy";
			conor = DriverManager.getConnection(url, user, password);
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		if (conor == null) {
			System.out.println("获取数据库连接失败！");
		}
		return conor;
	}

	/**
	 * 用JDBC方式从Mysql获取连接
	 * @return
	 */
	public Connection getConnectionFromMysql() {
		Connection conmy = null;
		try {

			// Class.forName("org.gjt.mm.mysql.Driver");
			Class.forName("com.mysql.jdbc.Driver");
			// String url =
			// "jdbc:mysql://localhost/mydb?user=root&password=root&useUnicode=true&characterEncoding=8859_1";
			String url = "jdbc:mysql://localhost:3306/test?autoReconnect=true&amp;characterEncoding=GBK&amp;zeroDateTimeBehavior=convertToNull&amp;transformedBitIsBoolean=true";
			String username = "tripagent";
			String password = "tripagent";
			// myDB为数据库名
			conmy = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (SQLException e1) {
			e1.printStackTrace();
		}
		if (conmy == null) {
			System.out.println("获取数据库连接失败！");
		}
		return conmy;
	}

	public Connection getConnectionFromDS(){
		Context ctx;
		DataSource ds;
		Connection con = null;
		try {
			ctx = new InitialContext();
			ds = (DataSource)ctx.lookup("java:comp/env/yehy");
			con = ds.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (con == null) {
			System.out.println("获取数据库连接失败！");
		}
		return con;
	}
	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		ConnectDB db = new ConnectDB();
		Connection cn = db.getConnectionFromMysql();
		try {
			cn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
